package com.zhanglijie.improve.atomic.three;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/9/6 0006 23:40
 */
public class AtomicRefenceDemoOne {
    static AtomicReference<Member> reference = new AtomicReference<Member>(new Member(1,"zhangsan",500));

    public static void main(String[] args) {
        AtomicInteger size = new AtomicInteger();
        for (int i = 0; i < 20000; i++) {
            new Thread(()->{
                while (true){
                    Member member = reference.get();
                    Member member1 = new Member(member.getNo(), member.getName(), member.getAmount() + 1);
                    if(reference.compareAndSet(member,member1)){
                        size.getAndIncrement();
                        System.out.println(member1);
                        break;
                    }
                }

            }).start();

        }
        try{
            Thread.sleep(5000);
        }catch (Exception e){}
        System.out.println(size.get());
    }
}
